package com.reliable.service.serviceimpl;

import com.reliable.service.domain.ReliableIpGeoCache;
import com.reliable.service.iplocation.ipdomain.IPInfo;
import com.reliable.service.iplocation.service.IPLocationService;
import com.reliable.service.mapper.ReliableIpGeoCacheMapper;
import com.reliable.service.service.IReliableIpGeoCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * IP地理位置结构化缓存Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-10
 */
@Service
@Slf4j
public class ReliableIpGeoCacheServiceImpl extends ServiceImpl<ReliableIpGeoCacheMapper, ReliableIpGeoCache> implements IReliableIpGeoCacheService {



    @Autowired
    private IPLocationService ipLocationService;

    @Autowired
    private ReliableIpGeoCacheMapper ipGeoCacheMapper;

    @Override
    public void ensureIpCached(String ip) {
        if (!isValidIp(ip)) return;
        if (ipGeoCacheMapper.existsByIp(ip) > 0) return;

        IPInfo info = ipLocationService.parseIp(ip);
        ReliableIpGeoCache cache = new ReliableIpGeoCache();
        cache.setIp(ip);
        cache.setCountry(safeGet(info.getCountry()));
        cache.setProvince(safeGet(info.getProvince()));
        cache.setCity(safeGet(info.getCity()));
        cache.setIsp(safeGet(info.getIsp()));
        ipGeoCacheMapper.insert(cache);
        log.debug("✅ IP 缓存: {}", ip);
    }

    @Override
    public void ensureIpsCached(Set<String> ips) {
        if (ips == null) return;
        ips.stream().filter(this::isValidIp).forEach(this::ensureIpCached);
    }

    private boolean isValidIp(String ip) {
        return ip != null && !ip.trim().isEmpty() && !"未知".equals(ip) && !"查询失败".equals(ip);
    }

    private String safeGet(String s) {
        return StringUtils.hasText(s) && !"0".equals(s) && !"未知".equals(s) ? s : null;
    }

}